package org.xhnews.parsers;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Vector;

import org.xhnews.log.RaspberryLogger;
import org.xhnews.to.WeatherItem;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

public class WeatherPullXMLParser {
	// 解析资讯列表
	public static Vector readWeatherItems(InputStream inputStream,
			String inputEncoding) {
		try {
			// 创建Pull解析
			XmlPullParserFactory pullParserFactory = XmlPullParserFactory
					.newInstance();
			XmlPullParser pullParser = pullParserFactory.newPullParser();
			// 解析XML
			Reader reader = new InputStreamReader(inputStream, inputEncoding);
			reader.read();
			pullParser.setInput(reader);
			// 开始
			int eventType = pullParser.getEventType();
			Vector items = null;
			WeatherItem item = null;
			boolean fristGif = true;

			while (eventType != XmlPullParser.END_DOCUMENT) {
				String nodeName = pullParser.getName();
				switch (eventType) {
				// 文档开始
				case XmlPullParser.START_DOCUMENT:
					items = new Vector();
					break;
				// 节点开始
				case XmlPullParser.START_TAG:
					if ("day".equals(nodeName)) {
						// 资讯节点开始
						item = new WeatherItem();
					} else if ("date".equals(nodeName)) {
						item.setDate(pullParser.nextText());
					} else if ("weather".equals(nodeName)) {
						item.setWeatherDescription(pullParser.nextText());
					} else if ("temp".equals(nodeName)) {
						item.setTemperature(pullParser.nextText());

					} else if ("wind".equals(nodeName)) {
						item.setWind(pullParser.nextText());
					} else if ("gif".equals(nodeName)) {
						if (fristGif) {
							item.setWeatherPicture1(pullParser.nextText());
						} else {
							item.setWeatherPicture2(pullParser.nextText());
						}
						fristGif = !fristGif;
					}
					break;
				// 节点结束
				case XmlPullParser.END_TAG:
					if ("day".equals(nodeName)) {
						items.addElement(item);
						item = null;
					}
					break;
				}
				eventType = pullParser.next();
			}// end while
			return items;
		} catch (Exception e) {
			RaspberryLogger.getInstance().info(e.getMessage());
			e.printStackTrace();
			return null;
		}
	}
}
